package com.example.cosplay.service.impl;

import com.example.cosplay.model.WallpaperResponse;
import com.example.cosplay.service.WallpaperService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
@Slf4j
public class WallpaperServiceImpl implements WallpaperService {

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;
    private final String apiUrl = "https://api.vvhan.com/api/wallpaper/pcGirl?type=json";
    private final String defaultDownloadDir = "E:\\autoImg";

    public WallpaperServiceImpl(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    @PostConstruct
    public void init() {
        // Create default download directory if it doesn't exist
        ensureDirectoryExists(defaultDownloadDir);
    }
    
    private void ensureDirectoryExists(String directoryPath) {
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            log.info("创建目录: {}", directoryPath);
            if (directory.mkdirs()) {
                log.info("目录创建成功");
            } else {
                log.error("无法创建目录: {}", directoryPath);
            }
        }
    }

    @Override
    public String fetchAndDownloadWallpaper() {
        return fetchAndDownloadWallpaper(defaultDownloadDir);
    }
    
    @Override
    public String fetchAndDownloadWallpaper(String downloadPath) {
        // 确保下载目录存在
        ensureDirectoryExists(downloadPath);
        
        try {
            // Fetch wallpaper data from API
            log.info("从API获取壁纸数据: {}", apiUrl);
            String response = restTemplate.getForObject(apiUrl, String.class);
            WallpaperResponse wallpaperResponse = objectMapper.readValue(response, WallpaperResponse.class);
            
            if (wallpaperResponse != null && wallpaperResponse.isSuccess()) {
                log.info("成功获取壁纸URL: {}", wallpaperResponse.getUrl());
                // Download the image
                return downloadImage(wallpaperResponse.getUrl(), downloadPath);
            } else {
                log.error("API返回失败响应");
                return "获取壁纸失败: API返回失败响应";
            }
        } catch (Exception e) {
            log.error("获取壁纸时出错", e);
            return "获取壁纸时出错: " + e.getMessage();
        }
    }

    private String downloadImage(String imageUrl, String downloadDir) {
        try {
            // Generate a unique filename based on current timestamp
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileExtension = getFileExtension(imageUrl);
            String fileName = "wallpaper_" + timestamp + fileExtension;
            String filePath = downloadDir + File.separator + fileName;
            
            log.info("开始从以下地址下载图片: {}", imageUrl);
            log.info("将保存至: {}", filePath);
            
            // Open connection to the URL and download the image with progress tracking
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            int fileSize = connection.getContentLength();
            
            try (InputStream in = connection.getInputStream();
                 FileOutputStream out = new FileOutputStream(filePath)) {
                
                byte[] buffer = new byte[4096];
                int bytesRead;
                long totalBytesRead = 0;
                int previousProgress = 0;
                
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    
                    // Calculate and log progress every 10%
                    if (fileSize > 0) {
                        int progress = (int) (totalBytesRead * 100 / fileSize);
                        if (progress >= previousProgress + 10) {
                            previousProgress = progress;
                            log.info("下载进度: {}% ({}/{} 字节)", 
                                    progress, totalBytesRead, fileSize);
                        }
                    }
                }
            }
            
            log.info("图片成功下载至: {}", filePath);
            return "Image successfully downloaded to: " + filePath;
        } catch (IOException e) {
            log.error("下载图片时出错", e);
            return "下载图片时出错: " + e.getMessage();
        }
    }
    
    private String getFileExtension(String url) {
        // Extract file extension from URL
        String extension = url.substring(url.lastIndexOf('.'));
        // If the extension is too long or contains query parameters, default to .jpg
        if (extension.length() > 5 || extension.contains("?")) {
            extension = ".jpg";
        }
        return extension;
    }
} 